import { ColorType } from '@/interface/Basic'
// RGB to HEX
export function HEXtoRGB(str: string) {
  const reg = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/
  if (!reg.test(str)) return
  let newStr = str.toLowerCase().replace('#', '')
  const len = newStr.length
  if (len === 3) {
    let t = ''
    for (let i = 0; i < len; i++) {
      t += newStr.slice(i, i + 1).concat(newStr.slice(i, i + 1))
    }
    newStr = t
  }
  const arr = [] // 将字符串分隔，两个两个的分隔
  for (let i = 0; i < 6; i = i + 2) {
    const s = newStr.slice(i, i + 2)
    arr.push(parseInt('0x' + s))
  }
  return 'rgb(' + arr.join(',') + ')'
}

export function RGBToHEX(str: string) {
  const reg = /^(rgb|RGB)/
  if (!reg.test(str)) return ''
  const start = str.indexOf('(')
  const end = str.indexOf(')')
  const arr = str
    .substring(start + 1, end)
    .split(',')
    .slice(0, 3)
  let color = '#'
  for (let i = 0; i < arr.length; i++) {
    let t = Number(arr[i]).toString(16)
    if (t === '0') {
      t = t + '0'
    }
    color += t
  }
  return color.toUpperCase()
}

export const formatColor = (color?: ColorType) => {
  if (!color) return '#CECECE'
  // 16进制模式
  let stringColor = color.toString()
  if (/^#[1-9A-Fa-f]{1,6}$/.test(stringColor)) {
    const len = stringColor.length
    if (len < 7) {
      while (stringColor.length < 7) {
        stringColor += stringColor[stringColor.length - 1]
      }
    } else if (len > 7) {
      stringColor = stringColor.slice(0, 7)
    }
  } else if (/^(rgb|RGB)/.test(stringColor)) {
    stringColor = RGBToHEX(stringColor)
  } else {
    stringColor = '#CECECE'
  }
  return stringColor.toUpperCase()
}
